package com.example.sharesinfo.fragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.sharesinfo.R;
import com.example.sharesinfo.base.BaseFragment;
import com.example.sharesinfo.bean.PersonalCenterBean;
import com.example.sharesinfo.bean.TextBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.fragment.index.IStockFragment;
import com.example.sharesinfo.fragment.index.MoneyManagerFragment;
import com.example.sharesinfo.helper.GlideHelper;
import com.example.sharesinfo.manager.CloudManager;
import com.example.sharesinfo.model.ChatRecordModel;
import com.example.sharesinfo.ui.ChatActivity;
import com.example.sharesinfo.ui.ChatRecordActivity;
import com.example.sharesinfo.ui.MeActivity;
import com.example.sharesinfo.ui.PersonalCenterActivity;
import com.example.sharesinfo.ui.SearchActivity;
import com.example.sharesinfo.ui.SharesInfoActivity;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.google.gson.Gson;

import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import de.hdodenhof.circleimageview.CircleImageView;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.message.TextMessage;


public class IndexFragment extends BaseFragment implements View.OnClickListener {
    private IndexFragment fa;
    private Fragment[] fragments = {new IStockFragment().getFragment()
    };
    private int currentTabIndex;

    private CircleImageView headImage;
    private String headImageUrl;
    //私信
    private ImageButton message_btn;
    //测试聊天
    private ImageButton ai_btn;
    private ImageButton search_btn;
    private static final int H_TIME_WHAT = 1000;
    private ImageView iv_yellow_point;

    public IndexFragment getFragment() {
        if (fa == null) {
            fa = new IndexFragment();
        }
        return fa;
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    PersonalCenterBean result = (PersonalCenterBean) msg.obj;
                    MeActivity.startActivity(getContext(), result);
                    //PersonalCenterActivity.startActivity(getContext(), result, false);
                    break;
                case 404:
                    break;
                case H_TIME_WHAT:
                    if (CloudManager.getInstance().isConnect()) {
                        LogUtils.i("测试链接：" + "连接成功");
                        queryChatRecord();
                    } else {
                        LogUtils.i("测试链接：" + "失败");
                        mHandler.sendEmptyMessageDelayed(H_TIME_WHAT, 1000);
                    }
                    break;
            }
            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_index, null);
        initView(view);
        changeHomeFragment(0);

        return view;
    }

    private void initView(View view) {
        iv_yellow_point = view.findViewById(R.id.iv_yellow_point);
        headImage = view.findViewById(R.id.my_head_image);
        headImageUrl = SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, "");
        GlideHelper.loadUrl(getContext(), headImageUrl, headImage);
        headImage.setOnClickListener(this);
        message_btn = view.findViewById(R.id.message_btn);
        message_btn.setOnClickListener(this);
        ai_btn = view.findViewById(R.id.ai_btn);
        ai_btn.setOnClickListener(this);
        search_btn = view.findViewById(R.id.search_btn);
        search_btn.setOnClickListener(this);
    }

    private void changeHomeFragment(int index) {
        FragmentManager supportFragmentManager = getFragmentManager();
        if (supportFragmentManager != null) {
            FragmentTransaction transaction = supportFragmentManager.beginTransaction();
            transaction.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                transaction.add(R.id.main_home_container, fragments[index]);
            }
            transaction.show(fragments[index]).commit();
        }
    }

    private void queryChatRecord() {
        mHandler.removeMessages(H_TIME_WHAT);
        final int[] sum = {0};
        CloudManager.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {

                if (CommonUtils.isEmpty(conversations)) {
                    for (int i = 0; i < conversations.size(); i++) {
                        Conversation c = conversations.get(i);
                        sum[0] += c.getUnreadMessageCount();
                    }
                    if (sum[0] > 0) {
                        iv_yellow_point.setVisibility(View.VISIBLE);
                    } else {
                        iv_yellow_point.setVisibility(View.GONE);
                    }
                }

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_head_image:
                queryUserInfo();
                break;
            case R.id.message_btn:
                startActivity(new Intent(getContext(), ChatRecordActivity.class));
                break;
            case R.id.ai_btn:
                startActivity(new Intent(getContext(), SharesInfoActivity.class));
//                ChatActivity.startActivity(getContext(), "13", "高昶",
//                        SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, ""));
                break;
            case R.id.search_btn:
                startActivity(new Intent(getContext(), SearchActivity.class));
                break;
        }
    }

    private void queryUserInfo() {
        String url = "http://119.23.221.142/api/user/GetHomePage?UserId=" + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                LogUtils.i("PersonalCenterActivity:" + s);
                PersonalCenterBean bean = new Gson().fromJson(s, PersonalCenterBean.class);
                message.what = code;
                message.obj = bean;
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.i("index" + "onResume");
        if (!headImageUrl.equals(SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, ""))) {
            headImageUrl = SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, "");
            GlideHelper.loadUrl(getContext(), headImageUrl, headImage);
        }
        //开始计时
        mHandler.sendEmptyMessage(H_TIME_WHAT);
    }

}
